const app = getApp()
const base64 = require('../../utils/base64.js')

Page({
	data: {
		code_id: '',
		is_show:true,
		to_home:true,
		to_shop:true
	},

	onLoad: function (options) {
		this.setData(options)
		if (options._id) {
			wx.setNavigationBarTitle({
				title: '编辑项目',
			})
			this.load(options._id)
		}
	},
	scan() {
		wx.scanCode({
			complete: (res) => {
				console.log(res)
				if (res.errMsg == "scanCode:ok" && res.scanType == "QR_CODE") {
					let code = base64.decode(res.result)
					if (!code || code.substr(0, 5) != 'rule|') {
						return wx.showToast({
							title: '二维码不正确',
							icon: 'none'
						})
					}
					code = code.substr(5)
					//code = '123'
					app.db.collection('code').doc(code).get({
						success: res => {
							console.log(res.data)
							wx.showModal({
								title:'扫描结果',
								content:'是否选择'+res.data.name+"("+res.data.interval+"天内可预约"+res.data.times+"次)",
								success:rs=>{
									if(rs.confirm){
										this.setData({code:res.data})
									}
								}
							})
						},
						fail: res => {
							console.error(res)
							wx.showToast({
								title: '未找到校验规则',
								icon:'none'
							})
						}
					})


				} else {
					wx.showToast({
						title: '无法识别',
						icon: 'none'
					})
				}
			},
		})
	},
	showModal(e) {
		app.db.collection('code').where({shop_id:this.data.shop_id}).get().then(res=>{
			this.setData({
				modalName: e.currentTarget.dataset.mod,
				codelist:res.data
			})
		})
		
	},
	hideModal() {
		this.setData({
			modalName: ''
		})
	},
	chooseCode(e) {
		this.setData({
			code: this.data.codelist[e.currentTarget.dataset.ind],
			modalName: ''
		})
	},
	changeType(e){
		let to_home=  false,to_shop = false
		e.detail.value.forEach(function(n){
			if(n=='to_home') to_home = true;
			else if (n=='to_shop') to_shop = true
		})
		this.setData({
			to_home,
			to_shop
		})
	},
	load(id){
		app.db.collection('product').doc(id).get().then(res=>{
			this.setData(res.data)
			if(res.data.code_id){
				app.db.collection('code').doc(res.data.code_id).get().then(res=>{
					this.setData({code:res.data})
				})
			}
		})
	},
	onSubmit(e){
		let data = e.detail.value
		if (!data.name) {
			return wx.showToast({
				title: '请输入名称',
				icon: 'none'
			})
		}
		if(data.price.length==0){
			return wx.showToast({
				title: '请输入价格',
				icon: 'none'
			})
		}
		if(parseFloat(data.price)<0){
			return wx.showToast({
				title: '价格必须大于等于0',
				icon: 'none'
			})
		}
		if(this.data._id){
			data._id = this.data._id
		}
		if(this.data.code)data.code_id = this.data.code._id
		data.to_home = this.data.to_home
		data.to_shop = this.data.to_shop
		data.shop_id= this.data.shop_id
		app.cloud({
			name: 'shopProduct',
			data,
			loading: '提交中',
			def: true,
			success: res => {
				wx.showToast({
					title: res.msg,
				})
				//读取db
				this.load(res.data)
				wx.setNavigationBarTitle({
				  title: '编辑项目',
				})
			}
		})
	}
})